package cn.coderliu.aspect;

import cn.coderliu.config.RedisUtil;
import cn.coderliu.entty.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author liu
 */
@Component
@Aspect
public class LockAspect {
    @Autowired
    RedisUtil redisUtil;

    @Pointcut("@annotation(cn.coderliu.aspect.Lock)")
    public void lockPointcut() {
    }


    @Before("lockPointcut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        User u = (User) (joinPoint.getArgs()[0]);
        String methodName = joinPoint.getSignature().getDeclaringTypeName();
        String key = methodName + "_"+ u.getId().toString();
        redisUtil.lock(key);
        System.out.println("已经锁定key为" + key);
        System.out.println(joinPoint.getSignature().getDeclaringTypeName());
        System.out.println(u.toString());
    }

    @After("lockPointcut()")
    public void doAfter(JoinPoint joinPoint) throws Throwable {
        User u = (User) (joinPoint.getArgs()[0]);
        String methodName = joinPoint.getSignature().getDeclaringTypeName();
        String key = methodName + "_"+ u.getId().toString();
        redisUtil.del(key);
        System.out.println("已经解锁key为" + key);
        System.out.println(joinPoint.getSignature().getDeclaringTypeName());
        System.out.println(u.toString());
    }

}
